package tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author way
 * @create 2025-02-08 23:14
 */
public class _111_minDepth {
    public int minDepth(TreeNode root) {
        if (root == null) return 0;

        int leftDepth = minDepth(root.left);
        int rightDepth = minDepth(root.right);

        if (root.left == null && root.right != null) {
            return 1 + rightDepth;
        } else if (root.left != null && root.right == null) {
            return 1 + leftDepth;
        }else {
            return Math.min(leftDepth,rightDepth)+1;
        }
    }

    public int minDepth1(TreeNode root) {
        if (root == null) return 0;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int minDepth = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            minDepth++;
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);

                if (node.left == null && node.right == null) {
                    return minDepth;
                }
            }
        }
        return minDepth;
    }
}
